package controllers

import (
	"SuNing/models"
	"encoding/json"
	"fmt"
	beego "github.com/beego/beego/v2/server/web"
	"path/filepath"
	"strconv"
	"strings"
)

type GoodsController struct {
	beego.Controller
}

func (c *GoodsController) Adds() {
	name := c.GetString("name")
	price, _ := c.GetFloat("price")
	img := c.GetString("img")
	intro := c.GetString("intro")
	goods := models.Goods{
		Name:  name,
		Price: price,
		Img:   img,
		Intro: intro,
	}
	if name == "" { // 验证商品名称
		c.Data["json"] = Json{
			Code: 500,
			Msg:  "名字不能为空",
			Data: nil,
		}
		c.ServeJSON()
		return
	}
	if price <= 0 { // 验证价格
		c.Data["json"] = Json{
			Code: 500,
			Msg:  "请输入有效的数子",
			Data: nil,
		}
		c.ServeJSON()
		return
	}
	//文件类型
	allowExt := strings.ToLower(img)
	Ext := map[string]bool{
		".png":  true,
		".jpg":  true,
		".jpeg": true,
	}
	if !Ext[allowExt] {
		c.Data["json"] = Json{
			Code: 500,
			Msg:  "文件类型错误只支持格式png，jpg",
			Data: nil,
		}
		c.ServeJSON()
		return
	}
	if intro == "" { // 验证商品名称
		c.Data["json"] = Json{
			Code: 500,
			Msg:  "描述不能为空",
			Data: nil,
		}
		c.ServeJSON()
		return
	}
	err := models.Add(&goods)
	if err != nil {
		c.Data["json"] = Json{
			Code: 500,
			Msg:  "添加失败",
			Data: nil,
		}
		c.ServeJSON()
	} else {
		c.Data["json"] = Json{
			Code: 200,
			Msg:  "添加成功",
			Data: goods,
		}
		c.ServeJSON()
	}
}
func (c *GoodsController) Upload() {
	file, header, err := c.GetFile("img")
	if err != nil {
		c.Data["json"] = Json{
			Code: 500,
			Msg:  "文件获取失败",
			Data: nil,
		}
		c.ServeJSON()
	}
	defer file.Close()
	//文件大小
	if header.Size > 2*1024*1024 {
		c.Data["json"] = Json{
			Code: 500,
			Msg:  "文件过大 不能超过2M",
			Data: nil,
		}
		c.ServeJSON()
		return
	}
	//文件类型
	allowExt := strings.ToLower(filepath.Ext(header.Filename))
	Ext := map[string]bool{
		".png": true,
		".jpg": true,
	}
	if !Ext[allowExt] {
		c.Data["json"] = Json{
			Code: 500,
			Msg:  "文件类型错误只支持格式png，jpg",
			Data: nil,
		}
		c.ServeJSON()
		return
	}
	//定义文件保存路径
	path := "static/img/" + header.Filename
	err = c.SaveToFile("img", path)
	if err != nil {
		c.Data["json"] = Json{
			Code: 500,
			Msg:  "文件上传失败",
			Data: nil,
		}
		c.ServeJSON()
	} else {
		imgSrc := "http://localhost:8080/" + path
		c.Data["json"] = Json{
			Code: 200,
			Msg:  "文件上传成功",
			Data: imgSrc,
		}
		c.ServeJSON()
	}

}
func (c *GoodsController) List() {

	list, err := models.List()
	if err != nil {
		c.Data["json"] = Json{
			Code: 500,
			Msg:  "展示失败",
			Data: nil,
		}
		c.ServeJSON()
	} else {
		c.Data["json"] = Json{
			Code: 200,
			Msg:  "展示成功",
			Data: list,
		}
		c.ServeJSON()
	}
}
func (c *GoodsController) Show() {
	id, _ := c.GetInt("id")
	key := "goods-" + strconv.Itoa(id)
	number := strconv.Itoa(id)
	models.Rdb.ZIncrBy("goods-rank", 1, number)
	var goods models.Goods
	val, err := models.Rdb.Get(key).Result()
	if err != nil {
		err = models.Db.Model(&goods).Where("id = ?", id).First(&goods).Error
		if err != nil {
			c.Data["json"] = Json{
				Code: 500,
				Msg:  "详情展示失败",
				Data: nil,
			}
			c.ServeJSON()
		} else {
			jsonByte, _ := json.Marshal(goods)
			models.Rdb.Set(key, string(jsonByte), 0)
			c.Data["json"] = Json{
				Code: 200,
				Msg:  "详情展示成功-mysql",
				Data: goods,
			}
			c.ServeJSON()
		}
	} else {
		json.Unmarshal([]byte(val), &goods)
		c.Data["json"] = Json{
			Code: 200,
			Msg:  "展示成功-redis",
			Data: goods,
		}
		c.ServeJSON()
	}

}
func (c *GoodsController) Page() {
	c.Ctx.Output.Header("Access-Control-Allow-Origin", "*")
	page, _ := c.GetInt("p", 1)
	size, _ := c.GetInt("s", 3)
	name := c.GetString("name")
	minPrice, _ := c.GetFloat("minPrice")
	maxPrice, _ := c.GetFloat("maxPrice")
	key := "page" + "-" + strconv.Itoa(page) + "-" + strconv.Itoa(size)
	val, err := models.Rdb.Get(key).Result()
	pageDate := make(map[string]interface{})
	if err != nil {
		goods, count, err := models.Page(page, size, name, minPrice, maxPrice)
		if err != nil {
			c.Data["json"] = Json{
				Code: 500,
				Msg:  "分页展示失败",
				Data: nil,
			}
			c.ServeJSON()
		} else {

			pageDate["goods"] = goods
			pageDate["count"] = count
			jsonByte, _ := json.Marshal(pageDate)
			models.Rdb.Set(key, string(jsonByte), 0)
			c.Data["json"] = Json{
				Code: 200,
				Msg:  "分页展示成功-mysql",
				Data: pageDate,
			}
			c.ServeJSON()
		}
	} else {
		json.Unmarshal([]byte(val), &pageDate)
		c.Data["json"] = Json{
			Code: 200,
			Msg:  "分页成功-redis",
			Data: pageDate,
		}
		c.ServeJSON()
	}

}
func (c *GoodsController) GoodsRank() {
	result, err := models.Rdb.ZRevRange("goods-rank", 0, 9).Result()
	if err != nil {
		c.Data["json"] = Json{
			Code: 500,
			Msg:  "展示失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	}
	fmt.Println(result)
	var rankSlice []models.Goods
	for _, s := range result {
		var video models.Goods
		models.Db.Where("id = ?", s).First(&video)
		rankSlice = append(rankSlice, video)
	}
	c.Data["json"] = Json{
		Code: 200,
		Msg:  "排行帮展示成功",
		Data: rankSlice,
	}
	c.ServeJSON()
}
func (c *GoodsController) Update() {
	name := c.GetString("name")
	price, _ := c.GetFloat("price")
	img := c.GetString("img")
	intro := c.GetString("intro")
	id, _ := c.GetInt("id")
	goods := models.Goods{
		Name:  name,
		Price: price,
		Img:   img,
		Intro: intro,
	}
	err := models.Db.Where("id = ?", id).Updates(&goods).Error
	if err != nil {
		c.Data["json"] = Json{
			Code: 500,
			Msg:  "修改失败",
			Data: nil,
		}
		c.ServeJSON()
	} else {

		c.Data["json"] = Json{
			Code: 200,
			Msg:  "修改成功",
			Data: goods,
		}
		c.ServeJSON()
	}
}
func (c *GoodsController) Del() {
	id, _ := c.GetInt("id")
	err := models.Del(id)
	if err != nil {
		c.Data["json"] = Json{
			Code: 500,
			Msg:  "删除失败",
			Data: nil,
		}
		c.ServeJSON()
	} else {
		c.Data["json"] = Json{
			Code: 200,
			Msg:  "删除成功",
			Data: nil,
		}
		c.ServeJSON()
	}
}
